<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .box{
      width: 200px;
      height: 200px;
      background: rgb(207, 48, 85);
      position: absolute;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <script>
    //获取 box 元素
    let box = document.querySelector('.box');
    let l=0,x=0;
    //声明一个变量
    let isDown = false;//默认鼠标未按下
    //绑定鼠标按下事件  down 向下
    box.onmousedown = function(e){
      //获取 div 距离父级左侧的偏移
      l = box.offsetLeft;
      //获取鼠标水平方向的偏移
      x = e.clientX;
      //修改变量的值
      isDown = true;
    }

    //绑定鼠标移动事件
    window.onmousemove = function(e){
      //判断鼠标是否按下
      if(!isDown) return;
      //获取鼠标移动之后的水平位置
      let _x = e.clientX;
      //计算
      let newLeft = _x - (x - l);
      //修改div的样式
      box.style.left = newLeft + 'px';
    }

    //绑定鼠标的抬起事件
    box.onmouseup = function(){
      //修改变量的值
      isDown = false;
    }

  </script>
</body>
</html>